﻿using System;
using System.Web.UI;

namespace ReadyApps.Common
{
    static class WebUtilities
    {
        /// <summary>
        /// Searches a control tree for a control with the given control ID including the
        /// control passed to the method.
        /// </summary>
        /// <param name="baseControl">The control to start the hierarchical search from</param>
        /// <param name="controlID">The control ID to search for</param>
        /// <returns>A control that with the matching ID, or <c>null</c> if not found.</returns>
        public static Control FindControlRecursive(Control baseControl, string controlID)
        {
            if (string.IsNullOrEmpty(controlID))
            {
                throw new ArgumentNullException("controlID");
            }
            Control foundControl = null;
            if (baseControl != null)
            {
                if (baseControl.ID == controlID)
                {
                    foundControl = baseControl;
                }
                else
                {
                    foreach (Control control in baseControl.Controls)
                    {
                        foundControl = FindControlRecursive(control, controlID);
                        if (foundControl != null)
                        {
                            break;
                        }
                    }
                }
            }

            return foundControl;
        }
    }
}
